/**
 *
 * @ClassName ${NAME}
 * @Description
 * @author zhangyw
 * @date 16/12/13 10:57
 */

var http = (function ($) {
    var _self = {};
    _self._config = _self._config || {contextPath: '/api'};
    _self.config = function (options) {
        _self._config = options || _self._config;
        if (_self._config.contextPath == "") {
            _self._config.contextPath = "/";
        }
    };

    _self.buildReqUrl = function (path, params) {
        var _base = _self._config.contextPath;
        if (_base.lastIndexOf('/') == _base.length - 1) {
            _base = _base.substring(0, _base.length - 1);
        }

        if (path) {
            if (path.indexOf('/') == 0) {
                path = path.substring(1);
            }
            var _s;
            if (_base === '/') {
                _s = _base + path;
            } else {
                _s = _base + '/' + path;
            }

            if (params) {
                _s = _s + '?';
                for (var key in params) {
                    _s = _s + key + '=' + params[key] + '&';
                }
                if (_s.lastIndexOf('&') == _s.length - 1) {
                    _s = _s.substring(0, _s.length - 1);
                }
            }
            // console.log('req url:', _s);
            return _s;
        }
        throw new Error('path connot be null , please check');
    };

    /**
     * post请求
     * @param path
     * @param params
     * @param headers
     */
    _self.post = function (path, params, headers) {
        headers = _self.buildHead(headers);
        return $.ajax({
            url: _self.buildReqUrl(path),
            type: 'POST',
            data: params,
            dataType: 'json',
            headers: headers,
            success: success,
            fail: fail
        });
    };

    /**
     *
     * @param path
     * @param formData
     * @param headers
     * @returns {*}
     */
    _self.postFile = function (path, formData, headers) {
        headers = _self.buildHead(headers);
        return $.ajax({
            url: _self.buildReqUrl(path),
            type: 'POST',
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            headers: headers,
            success: success,
            fail: fail
        });
    };


    /**
     * post请求
     * @param path
     * @param params
     * @param headers
     */
    _self.get = function (path, params, headers) {
        headers = _self.buildHead(headers);
        return $.ajax({
            url: _self.buildReqUrl(path, params),
            type: 'GET',
            dataType: 'json',
            headers: headers,
            success: success,
            fail: fail
        });
    };

    _self.buildHead = function (headers) {
        headers = headers || {};
        return headers;
    };

    var success = function (res) {
        if (res.code == 401 || res.code == -401) {
            // $.globalMessenger().post({
            //     message: "认证失效，正在跳转至登录认证页面...",//提示信息
            //     id: '401',
            //     actions: {
            //         retry: {
            //             label: '立即跳转',
            //             phrase: 'TIME',
            //             auto: true,
            //             delay: 5,
            //             action: function () {
            //                 _self.route('login.html');
            //             }
            //         }
            //     }
            // });
            window.location.href = 'login.html';
        }
    };

    var fail = function (res) {
        console.error(res);
        if (res && res.code == 401 || res.code == -401) {
            // $.globalMessenger().post({
            //     message: "认证失效，正在跳转至登录认证页面...",//提示信息
            //     id: '401',
            //     actions: {
            //         retry: {
            //             label: '立即跳转',
            //             phrase: 'TIME',
            //             auto: true,
            //             delay: 5,
            //             action: function () {
            //                 _self.route('login.html');
            //             }
            //         }
            //     }
            // });
            window.location.href = 'login.html';
        }
    };

    _self.getRequest = function () {
        var name, value;
        var str = location.href; //取得整个地址栏
        var num = str.indexOf("?");
        str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]

        var arr = str.split("&"); //各个参数放到数组里
        var request = {};
        for (var i = 0; i < arr.length; i++) {
            num = arr[i].indexOf("=");
            if (num > 0) {
                name = arr[i].substring(0, num);
                value = decodeURIComponent(arr[i].substr(num + 1));
                request[name] = value;
            }
        }
        return request;
    };

    _self.route = function (path, params, target) {
        if (path) {
            var _s;
            if (path.indexOf('http') < 0) {
                var _base = _self._config.contextPath;
                if (path.indexOf(_base) === 0) { // 指定 path 包含contextPath, 不拼接basePath
                    _s = path;
                } else { // 不包含拼接basePath
                    if (path.indexOf('/') == 0) {
                        path = path.substring(1);
                    }

                    if (_base === '/') {
                        _s = _base + path;
                    } else {
                        _s = _base + '/' + path;
                    }
                }
            } else {
                _s = path;
            }

            if (params) {
                _s = _s + '?';
                for (var key in params) {
                    _s = _s + key + '=' + params[key] + '&';
                }
                if (_s.lastIndexOf('&') == _s.length - 1) {
                    _s = _s.substring(0, _s.length - 1);
                }
            }

            // console.log('req url:', _s);
            // 打开新页面，默认在当前窗口打开
            window.open(_s, target ? (target == '' ? '_self' : target) : '_self');
        } else
            throw new Error('path connot be null , please check');
    };

    return _self;
})(jQuery);

function initDataId(){
	return localStorage.getItem('menuids');
}